package com.tanhua.server.service;

import com.tanhua.autoconfig.template.ApiFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/28 16:42
 */

@Service
public class UserInfoService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private ApiFaceTemplate apiFaceTemplate;

    /**
     * 保存用户详细信息
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     *  头像更新
     * @param headPhoto
     * @param id
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        // 将图片上传到Oss
        String name = headPhoto.getOriginalFilename();
        InputStream is = headPhoto.getInputStream();
        String imageUrl = ossTemplate.upload(name, is);
        // 调用apiFace检测人脸
        boolean check = apiFaceTemplate.faceCheck(imageUrl);
        // 不存在人脸就从oos中删除
        if(!check){
            // 从oos中删除图片
            String substring = imageUrl.substring(imageUrl.indexOf("com/") + 4);
            ossTemplate.deleteFile(substring);
            throw new RuntimeException("没有检测到人脸");
        }

        // 人脸检测通过就将图片url保存到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Long.valueOf(id));
        userInfo.setAvatar(imageUrl);
        userInfo.setCoverPic(imageUrl);
        // 调用服务，更新接口
        userInfoApi.updateHead(userInfo);
    }

    /**
     * 根据id查询用户详细信息
     * @param userID
     * @return
     */
    public UserInfoVo findById(Long userID) {

        UserInfo userInfo = userInfoApi.findById(userID);

        // age类型不一样
        UserInfoVo vo = new UserInfoVo();

        // 给vo设置String类型的age，
        if(userInfo.getAge() != null){
            vo.setAge(userInfo.getAge().toString());
        }

        // 实体类之间的属性拷贝
        BeanUtils.copyProperties(userInfo, vo);
        return vo;
    }


    /**
     * 修改用户详细信息
     * @param id
     * @param userInfo
     */
    public void updateInfo(Long id, UserInfo userInfo) {

        // 设置id
        userInfo.setId(id);
        userInfoApi.updateInfo(userInfo);
    }
}
